/**
 * 一键查询
 */
define([
    "dojo/_base/declare",
    "esri/geometry/Point",
    "esri/geometry/Polygon",
    "esri/Graphic",
    "esri/geometry/SpatialReference",
    "esri/tasks/support/FeatureSet",
    "esri/tasks/QueryTask",
    "esri/tasks/support/Query",
    "esri/rest/identify",
    "esri/rest/support/IdentifyParameters",
    "esri/geometry/geometryEngine",
  ], function (declare,Point,Polygon,Graphic,SpatialReference,
               FeatureSet,QueryTask,Query,identify, IdentifyParameters,geometryEngine) {

    return declare(null, {
        /**
         * 成员属性
         * @type {string}
         */
        curQueryGemo:null,
        mapView: Context.view,//地图视图
        onQuerySucceed:null,//返回查询后的GDP列表，含geom值
        currentEventPoint:null,//当前点击的位置
        urls:{
            queryGdpUrl:'/admin/gdp/regionGdp/findGdpByYear',
            queryDQUrl:'/admin/gdp/regionGdp/findDQByYearAndDistrict',
            queryTopsisUrl:'/admin/gdp/regionGdp/findTopsisByYearAndDistrict',
        },
        /**
         * 获取素有通用的元素
         * (建议通过function的方式返回，防止因为缓存的原因导致元素事件无法激活)
         * @returns
         */
        elements:function(){//每次加载后均需要重新选择
            return{

            };
        },
        /**
         * 构造函数（初始化函数）
         */
        constructor: function () {
            this.init();
        },
        /**
         * 初始化函数
         */
        init:function () {
            this.initMenu();//需要在初始化完成后重新选择
            this.initUI();
            this.initUIEvent();
            this.initOpt();
        },
        initMenu:function () {
            this.mapView=Context.view;
        },
        initOpt:function () {
        },
        initUI:function(){

        },
        initUIEvent:function () {
            var that=this;
            //GDP查询
            // $("#test").on('click',function () {
            //     that.startGdpQuery('2018');
            //     // that.queryLayerInfo();
            // });
            that.mapView.on("click", (event) => {
                that.currentEventPoint=event;
                that.queryByPoint(event,"DQ");
            });
            const closePopupAction = {
                title:"关闭",
                id: "close-popup"
            };

            const DQPopupAction = {
                title:"熵值法",
                id: "dq-popup"
            };
            const TopsisPopupAction = {
                title:"TOPSIS",
                id: "topsis-popup"
            };
            Context.view.popup = {
                collapseEnabled : false, // 移除title点击折叠功能
                maxInlineActions:4,
                dockOptions: {
                    buttonEnabled: false // 隐藏固定标签页
                },
                actions: [DQPopupAction,TopsisPopupAction,closePopupAction] // 清空事件按钮 （缩放至、...）
            };

            Context.view.popup.on("trigger-action", (event) => {
                if (event.action.id === "close-popup") {
                    Context.view.popup.visible=false;
                }else if (event.action.id === "dq-popup") {
                    that.queryByPoint(that.currentEventPoint,"DQ");
                }else if (event.action.id === "topsis-popup") {
                    that.queryByPoint(that.currentEventPoint,"TOPSIS");
                }
            });

        },

        /**
         * 信息查询
         * @param serverUrl
         * @param layerId
         * @param geometry
         */
        startGdpQuery: function (type,year) {
            const that = this;
            try{
                let queryUrl=mapConfig.regionLayerConfig.layerUrl
                    +"/"+mapConfig.regionLayerConfig.layerId;
                let regionField=mapConfig.regionLayerConfig.regionField;
                let definitionExpression=regionField+" like '%%'";
                // let definitionExpression="行政 in ('龙岩市')";
                const queryTask = new QueryTask({
                    url: queryUrl,
                });
                const query = new Query();
                query.returnGeometry = true;
                query.outFields = mapConfig.regionLayerConfig.outFields;
                // query.outFields = ["*"];
                let geometry=that.curQueryGemo;//预留用于空间属性查询
                if(geometry!=null)
                    query.geometry = geometry;
                query.where=definitionExpression;
                queryTask.execute(query).then(function (result) {
                    //绘制结果
                    let features=result.features;
                    that.queryGdpDate(type,year,function (items) {
                        let results=[];
                        for(let i=0;i<items.length;i++){
                            let item=items[i];
                            let geom=that.findGeomByRegion(item.district,features);
                            if (geom!=null) {
                                item.geom = geom;
                                results.push(item);
                            }
                        }
                        let onSucceed=that.onQuerySucceed;
                        if (onSucceed!=null&&typeof onSucceed=="function")
                            that.onQuerySucceed(results);
                    });



                }).catch(function () {
                    layer.msg("查询结果出错，请检查服务！");
                });
            }catch (e) {
                layer.msg("查询结果出错，请检查服务！");
            }
        },

        /**
         * 通过行政区划名称查询GDP数据
         */
        findGeomByRegion:function(areaCode,features){
            let that=this;
            for(let i=0;i<features.length;i++){
                let feature=features[i];
                let attributes=feature.attributes;
                let regionValue=attributes[mapConfig.regionLayerConfig.regionField];
                if (regionValue===areaCode){
                    return feature.geometry;
                }
            }
        },

        /**
         * 查询GDP数据
         */
        queryGdpDate:function(type,year,onSucceed){
            let that=this;
            let url=that.urls.queryGdpUrl;
            if(type=="DQ"){
                url=that.urls.queryDQUrl;
            }else if(type=="TOPSIS"){
                url=that.urls.queryTopsisUrl;
            }
            $.ajax({
                url : url,
                data : {
                    year:year,
                },
                type : 'get',
                headers: {
                    // 'Authorization':CommonUtils.getToken()
                },//通过请求头来发送token
                dataType : 'json',
                async : true,
                success : function(result) {
                    if(CommonUtils.handlerRes(result)){
                        // alert(result.data);
                        if (typeof onSucceed=="function")
                            onSucceed(result.data);
                        return;
                    }

                },
                error : function(msg) {
                    alert(CommonUtils.getExceptionMsg());
                }
            });

        },


        /***
         * 通过点查询信息
         */
        queryByPoint:function (event,type) {
            var that=this;
            // var geometry=mapPoint.x+","+mapPoint.y;
            var queryUrl=mapConfig.regionLayerConfig.layerUrl+"/identify";

            var params;
            params = new IdentifyParameters();
            params.tolerance = 3;
            params.layerIds = [0];
            params.layerOption = "top";
            params.width = that.mapView.width;
            params.height = that.mapView.height;
            params.geometryType = "esriGeometryPoint";

            params.geometry = event.mapPoint;
            params.mapExtent = that.mapView.extent;

            identify.identify(queryUrl, params).then(function(response) {
                var results = response.results;

                return results.map(function (result) {
                    var feature = result.feature;
                    var url="";
                    var typeName="";
                    if(type=="DQ"){
                        url=that.urls.queryDQUrl;
                        typeName="熵值";
                    }else if(type=="TOPSIS"){
                        url=that.urls.queryTopsisUrl;
                        typeName="TOPSIS值";
                    }

                    var district=feature.attributes[mapConfig.regionLayerConfig.regionField];
                    $.ajax({
                        url : url,
                        data : {
                            district:district
                        },
                        type : 'get',
                        dataType : 'json',
                        async : false,
                        success : function(result) {
                            if(CommonUtils.handlerRes(result)){
                                // alert(result.data);
                                debugger
                                var datas=result.data;
                                var content="";
                                for(var i=0;i<datas.length;i++){
                                    feature.attributes["title"+i]=datas[i].title;
                                    feature.attributes["gdp"+i]=datas[i].gdp;
                                    var title="title"+i;
                                    var gdp="gdp"+i;
                                    content+= "<b>年份:</b> {"+title+"} " +
                                        "<b>指数值:</b> {"+gdp+"}<br>"
                                }
                                // feature.attributes=result.data[0];
                                // for(var i=0;i<result.data.length;i++){
                                //     content+='<b>年份:</b> '+result.data[i].title+' ;<b>指数值：</b>'+result.data[i].gdp;
                                // }
                                feature.popupTemplate = {
                                    title: district+"-"+typeName,
                                    content:content,
                                    actions:[]
                            };

                                return feature

                            }


                        },
                        error : function(msg) {
                            alert(CommonUtils.getExceptionMsg());
                        }
                    });
                    return feature;

                });
            }).then(function (response) {
                Context.view.popup.open({
                    features: response,
                    location: event.mapPoint
                });
            }); //
            // S


        }
    });
});


